using System;
using T.FAS.Runtime.Base.Entity;

namespace T.FAS.Runtime.DataAccess.SQLDom
{
    /// <summary>
    /// 统一处理异构DB特殊语法&转义等逻辑的工具
    /// </summary>
    public class DBCustomTools
    {
        public const string MySQLStr = "mysql";
        public const string MSSQLStr = "mssql";
        public const string PostgreSQLStr = "postgresql";
        /// <summary>
        /// 占位符
        /// </summary>
        public readonly static string TableHintPlaceholder = "{0}";
        public DatabaseType CurrentDB { get; private set; }

        public DBCustomTools(object instance)
        {
            if (instance is SelectSqlStaForMSS)
                CurrentDB = DatabaseType.SQLServer;
            else if (instance is SelectSqlStaForMySQL)
                CurrentDB = DatabaseType.MySQL;
            else if (instance is SelectSqlStaForPostgreSQL)
                CurrentDB = DatabaseType.PostgreSQL;
            else if (instance is string dbStr)
            {
                switch (dbStr.ToLower())
                {
                    case MSSQLStr:
                        CurrentDB = DatabaseType.SQLServer;
                        break;
                    case MySQLStr:
                        CurrentDB = DatabaseType.MySQL;
                        break;
                    case PostgreSQLStr:
                        CurrentDB = DatabaseType.PostgreSQL;
                        break;
                    default:
                        throw new Exception(string.Format(CommonStringClassSQLDom.DBCustomTools_,dbStr));
                }
            }
            else
                throw new Exception(CommonStringClassSQLDom.DBCustomTools_1);
        }

        /// <summary>
        /// 为特殊的sqlElement增加特殊的DB相关的语句，例如With(Nolock)
        /// </summary>
        /// <param name="sqlElement"></param>
        /// <returns></returns>
        public string Format(string sqlElement)
        {
            return FormatWithNolock(sqlElement);
        }

        private string FormatWithNolock(string sqlElement)
        {
            if (CurrentDB == DatabaseType.SQLServer)
            {
                return string.Format(sqlElement, "with(nolock)");
            }
            else
            {
                return string.Format(sqlElement, "");
            }
        }

        /// <summary>
        /// 处理特殊SQL，例如With(NoLock)
        /// </summary>
        /// <returns></returns>
        public string SpecialAppendSQL()
        {
            return AppendWithNolock();
        }

        /// <summary>
        /// 处理特殊SQL
        /// </summary>
        /// <returns></returns>
        private string AppendWithNolock()
        {
            if (CurrentDB == DatabaseType.SQLServer)
            {
                return " with(nolock) ";
            }
            else
            {
                return "";
            }
        }
    }
}
